//
//  MailboxMessageViewController.m
//  yunyan
//
//  Created by haichuang on 2018/4/4.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "MailboxMessageViewController.h"
#import "BRPlaceholderTextView.h"
#import "ReleaseResultsView.h"

#define kMaxTextCount 1000
@interface MailboxMessageViewController ()<UIScrollViewDelegate,UITextViewDelegate>
{
    float _TimeNUMX;
    float _TimeNUMY;
    int _FontSIZE;
    float allViewHeight;
    //备注文本View高度
    float noteTextHeight;
    
    int endPage;
    
    int curryPage;
}

@property (nonatomic, strong) UIScrollView *mianScrollView;
@property (nonatomic, strong) BRPlaceholderTextView *noteTextView;


//图片
@property (nonatomic,strong) UIImageView *photoImageView;

@property (nonatomic,strong) UIButton * sureBtn;
@property (nonatomic,strong) NSMutableDictionary * upDic;
@property (nonatomic,strong) NSMutableArray * photoArr;
@property (nonatomic,copy)   NSString * photoStr;
@property (nonatomic,copy)   NSString * star_level;
@property (nonatomic,copy)   NSString * modelUrl;
@property (nonatomic,copy) UITextField * textField;
@property (nonatomic , strong) NSArray * imageArr;


@end

@implementation MailboxMessageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self customNaviItemTitle:@"信箱留言" isLeft:YES];
    _TimeNUMX = 1;
    _TimeNUMY = 1.1;
    [self createUI];
    _imageArr =  [[NSArray alloc]init];
   // self.labelStr = @"注：上传不超过5张反馈图片";
}

/**
 *  取消输入
 */
- (void)viewTapped{
    [self.view endEditing:YES];
}
//#pragma mark 键盘出现
//-(void)keyboardWillShow:(NSNotification *)note
//{
//    self.view.frame = CGRectMake(0, 0-200*_TimeNUMY, ScreenWidth,ScreenHeight);
//}
//#pragma mark 键盘消失
//-(void)keyboardWillHide:(NSNotification *)note
//{
//    self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
//}

- (void)createUI{
    _mianScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth , ScreenHeight)];
    _mianScrollView.contentSize =CGSizeMake(ScreenWidth, ScreenHeight);
    _mianScrollView.bounces =YES;
    _mianScrollView.showsVerticalScrollIndicator = false;
    _mianScrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:_mianScrollView];
    [_mianScrollView setDelegate:self];
    self.showInView = _mianScrollView;
    
    /** 初始化collectionView */
    [self initPickerView];
    
    [self initViews];
    
    
}

/**
 *  初始化视图
 */
- (void)initViews{
    
    
    //文本输入框
    _noteTextView = [[BRPlaceholderTextView alloc]init];
    _noteTextView.layer.cornerRadius = 5;
    _noteTextView.layer.masksToBounds=YES;
    _noteTextView.keyboardType = UIKeyboardTypeDefault;
    //文字样式
    
    _noteTextView.maxTextLength = kMaxTextCount;
    [_noteTextView setTextColor:[UIColor blackColor]];
    _noteTextView.delegate = self;
    _noteTextView.font = [UIFont systemFontOfSize:15.5];
    _noteTextView.placeholder= @"请写下您想对我们说的话（500字以内）";
    self.noteTextView.returnKeyType = UIReturnKeyDone;
    [self.noteTextView setPlaceholderColor:[UIColor lightGrayColor]];
    [self.noteTextView setPlaceholderOpacity:1];
    _noteTextView.textContainerInset = UIEdgeInsetsMake(5, 8, 5, 15);
    
    //确定按钮
    self.sureBtn = [[UIButton alloc] init];
    self.sureBtn.backgroundColor = RGBA(81, 158, 238, 1);
    self.sureBtn.enabled =YES;
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = 5;
    [self.sureBtn setTitle: @"发布" forState:UIControlStateNormal];
    [self.sureBtn addTarget:self action:@selector(sureBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [_mianScrollView addSubview:_textField];
    [_mianScrollView addSubview:_noteTextView];
    
    
    [_mianScrollView addSubview:self.sureBtn];
    
    
    
    [self updateViewsFrame];
    
}



/**
 *  界面布局 frame
 */
- (void)updateViewsFrame{
    
    if (!allViewHeight) {
        allViewHeight = 0;
    }
    if (!noteTextHeight) {
        noteTextHeight = 100*_TimeNUMY;
    }
    
    
    //文本编辑框
    _noteTextView.frame = CGRectMake(10, _textField.frame.origin.y+_textField.frame.size.height+10*_TimeNUMY, ScreenWidth - 20, noteTextHeight);
    
    
    
    //photoPicker
    [self updatePickerViewFrameY:self.noteTextView.frame.origin.y + self.noteTextView.frame.size.height];
    
    self.sureBtn.frame = CGRectMake(10*_TimeNUMX, [self getPickerViewFrame].origin.y+[self getPickerViewFrame].size.height+30*_TimeNUMY, ScreenWidth-20*_TimeNUMX, 50);
    
    allViewHeight = self.sureBtn.frame.origin.y+self.sureBtn.frame.size.height+10*_TimeNUMY;
    
    _mianScrollView.contentSize = self.mianScrollView.contentSize = CGSizeMake(0,allViewHeight);
}
/**
 *  恢复原始界面布局
 */
-(void)resumeOriginalFrame{
    _textField.frame = CGRectMake(0,80, ScreenWidth, 20);
    //文本编辑框
    _noteTextView.frame = CGRectMake(0, 40*_TimeNUMY, ScreenWidth, noteTextHeight);
    
}

- (void)pickerViewFrameChanged{
    [self updateViewsFrame];
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //当前输入字数
    
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    [self textChanged];
    return YES;
}

//文本框每次输入文字都会调用  -> 更改文字个数提示框
- (void)textViewDidChangeSelection:(UITextView *)textView{
    //
    
    
    [self textChanged];
}

/**
 *  文本高度自适应
 */
-(void)textChanged{
    
    CGRect orgRect = self.noteTextView.frame;//获取原始UITextView的frame
    
    //获取尺寸
    CGSize size = [self.noteTextView sizeThatFits:CGSizeMake(self.noteTextView.frame.size.width, MAXFLOAT)];
    
    orgRect.size.height=size.height+10;//获取自适应文本内容高度
    
    
    //如果文本框没字了恢复初始尺寸
    if (orgRect.size.height > 100) {
        noteTextHeight = orgRect.size.height;
    }else{
        noteTextHeight = 100;
    }
    
    [self updateViewsFrame];
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.textField) {
        NSInteger kMaxLength = 10;
        NSString *toBeString = textField.text;
        NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; //ios7之前使用[UITextInputMode currentInputMode].primaryLanguage
        if ([lang isEqualToString:@"zh-Hans"]) { //中文输入
            UITextRange *selectedRange = [textField markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
            if (!position) {// 没有高亮选择的字，则对已输入的文字进行字数统计和限制
                if (toBeString.length > kMaxLength) {
                    textField.text = [toBeString substringToIndex:kMaxLength];
                }
            }
            else{//有高亮选择的字符串，则暂不对文字进行统计和限制
            }
        }else{//中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
            if (toBeString.length > kMaxLength) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }
        }
    }
}

#pragma mark - UIScrollViewDelegate
//用户向上偏移到顶端取消输入,增强用户体验
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0) {
        [self.view endEditing:YES];
    }
}

-(void)leftButtonEvent:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)sureBtnClicked{
    
    if (_isMailbox) {
        if (_noteTextView.text.length<6||_noteTextView.text==nil) {
            
            SHuiMBhudTextTimeStr(@"留言内容不能小于6个字");
            
        }else {
            
            [self RequestForMessage:_noteTextView.text];
        }
    }else{
        ReleaseResultsView *clearView = [[ReleaseResultsView alloc]init];
        clearView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        [[UIApplication sharedApplication].keyWindow addSubview:clearView];
    }
    
}



-(void)RequestForMessage:(NSString  *)messge{
    
    NSLog(@"self.imageArray = %@",self.bigImageArray);
    
    NSString *jsonString;
    NSMutableArray * img = @[].mutableCopy;
    if (img) {
        [img removeAllObjects];
    }
    if (self.bigImageArray.count>0) {
        for (int i = 0; i<self.bigImageArray.count; i++) {
            
            NSData *data = UIImageJPEGRepresentation(self.bigImageArray[i], 0.5);
            NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            NSString * imageStr = [NSString stringWithFormat:@"data:image/png;base64,%@",encodedImageStr];
            
            [img addObject:imageStr];
        }
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:img
                                                           options:kNilOptions
                                                             error:nil];
        
        jsonString = [[NSString alloc] initWithData:jsonData
                                           encoding:NSUTF8StringEncoding];
    }else{
        
        jsonString = @"";
    }
    
    
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"content": messge,
                           @"img":jsonString
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(mailBox_message_api ) andparameters:dic Success:^(id responseObject) {
        
        SHuiMBhudTextTimeStr(@"留言成功");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.navigationController popViewControllerAnimated:YES];
        });

    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"操作频繁，请稍后再试");
        }else if(responses.statusCode == 403){
             SHuiMBhudTextTimeStr(@"操作频繁，请稍后再试");
        }else {
             SHuiMBhudTextNetError;
        }
    }];
}


@end
